package com.github.aloxc.plugin.restplus.listener;

import com.github.aloxc.plugin.restplus.common.Consts;
import com.github.aloxc.plugin.restplus.entity.RequestHistory;
import com.github.aloxc.plugin.restplus.utils.JsonUtils;
import com.github.aloxc.plugin.restplus.test.RestRequest;
import com.github.aloxc.plugin.restplus.test.RestRequestListener;
import com.github.aloxc.plugin.restplus.test.RestResponse;
import com.github.aloxc.plugin.restplus.utils.ProjectUtil;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.stream.Collectors;

import static com.github.aloxc.plugin.restplus.common.Consts.HISTORY_FILE_EXTEND_NAME;

/**
 * @author leero
 */
public class RestRequestHistoryListener implements RestRequestListener {

    private String parentName;

    public RestRequestHistoryListener(String parentName) {
        this.parentName = parentName;
    }

    @Override
    public void listener(Project project, Module module, RestRequest request, RestResponse response, String message) {
        String url = request.getUrl();
        String service = request.getService();

        RequestHistory history = new RequestHistory();
        history.setUrl(url);
        history.setService(service);
        history.setTest(request.getScript());
        if(request.getHeaderList() != null) {
            history.setHeaderMap(request.getHeaderList().stream().collect(Collectors.toMap(k -> k.getName(), v -> v.getValue())));
        }
        if(request.getCookieList() != null) {
            history.setCookieMap(request.getCookieList().stream().collect(Collectors.toMap(k -> k.getName(), v -> v.getValue())));
        }
        if(request.getParameters() != null) {
            history.setParamMap(request.getParameters().stream().collect(Collectors.toMap(k -> k.getName(), v -> v.getValue())));
        }
        history.setBody(request.getBody());
        history.setHttpMethod(request.getHttpMethod());
        if(response == null){
            return;
        }
        if(message == null) {
            history.setContent(response.getContent());
            history.setStatusCode(response.getStatusCode());
            history.setTestResultList(response.getTestResultList());
        }else{
            history.setMessage(message);
        }
        try {
            String servicePath = ProjectUtil.getHistoryStorePath(project,module,parentName,service);
            VirtualFile path = LocalFileSystem.getInstance().findFileByPath(servicePath);
            if (path == null) {
                path = VfsUtil.createDirectories(servicePath);
            }
            String serviceFile = servicePath + "/" + (new Date()).getTime() + HISTORY_FILE_EXTEND_NAME;
            File file = new File(serviceFile);
            FileUtils.write(file, JsonUtils.toJson(history,true),"utf-8");
            path.refresh(true,false);
            VirtualFile[] children = path.getChildren();
            int size = children.length;
            if(size >= Consts.PER_REQUEST_HISTORY_COUNT){
                Arrays.stream(children).sorted((o1, o2) ->
                        (int)(Long.parseLong(o1.getName().replaceAll(HISTORY_FILE_EXTEND_NAME,""))
                                - Long.parseLong(o2.getName().replaceAll(HISTORY_FILE_EXTEND_NAME,""))))
                        .limit(size - Consts.PER_REQUEST_HISTORY_COUNT + 1)
                        .forEach(it-> {
                            new File(it.getPath()).delete();
                        });
            }
            path.refresh(true,false);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
